#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MCP Calculator Server - Enhanced Main Server

升级版MCP计算器服务器主文件
"""

import asyncio
import signal
import sys
import os
from pathlib import Path
from typing import Optional

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from mcp.server.fastmcp import FastMCP
from src.config import config_manager
from src.logging_utils import setup_logging, EnhancedLogger
from src.mcp_tools import EnhancedMCPTools

class EnhancedCalculatorServer:
    """增强版计算器服务器"""
    
    def __init__(self):
        self.mcp: Optional[FastMCP] = None
        self.logger: Optional[EnhancedLogger] = None
        self.tools: Optional[EnhancedMCPTools] = None
        self._shutdown_event = asyncio.Event()
        
    async def initialize(self):
        """初始化服务器"""
        try:
            # 设置日志
            self.logger = setup_logging(config_manager.logging_config.__dict__)
            self.logger.info("正在初始化增强版MCP计算器服务器...")
            
            # 创建MCP服务器实例
            self.mcp = FastMCP(
                name=config_manager.server_config.name,
                version=config_manager.server_config.version
            )
            
            # 初始化工具
            self.tools = EnhancedMCPTools(self.mcp, self.logger)
            
            # 设置信号处理
            self._setup_signal_handlers()
            
            self.logger.info(f"服务器初始化完成 - {config_manager.server_config.name} v{config_manager.server_config.version}")
            
        except Exception as e:
            if self.logger:
                self.logger.error(f"服务器初始化失败: {e}")
            else:
                print(f"服务器初始化失败: {e}")
            raise
    
    def _setup_signal_handlers(self):
        """设置信号处理器"""
        def signal_handler(signum, frame):
            self.logger.info(f"收到信号 {signum}，正在关闭服务器...")
            asyncio.create_task(self.shutdown())
        
        # 在Windows上只处理SIGINT
        if sys.platform == "win32":
            signal.signal(signal.SIGINT, signal_handler)
        else:
            signal.signal(signal.SIGINT, signal_handler)
            signal.signal(signal.SIGTERM, signal_handler)
    
    async def run(self):
        """运行服务器"""
        try:
            await self.initialize()
            
            self.logger.info("MCP计算器服务器正在运行...")
            self.logger.info("按 Ctrl+C 停止服务器")
            
            # 运行MCP服务器
            await self.mcp.run()
            
        except KeyboardInterrupt:
            self.logger.info("收到键盘中断信号")
        except Exception as e:
            self.logger.error(f"服务器运行错误: {e}")
            raise
        finally:
            await self.shutdown()
    
    async def shutdown(self):
        """关闭服务器"""
        if self._shutdown_event.is_set():
            return
        
        self._shutdown_event.set()
        
        try:
            if self.logger:
                self.logger.info("正在关闭服务器...")
            
            # 清理资源
            if self.tools and self.tools.history:
                # 保存历史记录
                try:
                    self.tools.history.cleanup_old_records()
                    if self.logger:
                        self.logger.info("历史记录已保存")
                except Exception as e:
                    if self.logger:
                        self.logger.error(f"保存历史记录失败: {e}")
            
            # 关闭日志
            if self.logger:
                self.logger.info("服务器已关闭")
                
        except Exception as e:
            if self.logger:
                self.logger.error(f"关闭服务器时出错: {e}")
            else:
                print(f"关闭服务器时出错: {e}")

def main():
    """主函数"""
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        sys.exit(1)
    
    # 创建并运行服务器
    server = EnhancedCalculatorServer()
    
    try:
        # 在Windows上使用ProactorEventLoop
        if sys.platform == "win32":
            asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
        
        asyncio.run(server.run())
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"服务器启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()